package com.mobi.Survey.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * Helper.java Provides different sort of helper utility
 * 
 * 
 */
public class Helper
{

	public static final String APP_FOLDER = "survey";

	public static final int toInt(String numString)
	{

		try
		{
			return Integer.parseInt(numString.trim());
		} catch (Exception e)
		{
			e.printStackTrace();
			return 0;
		}
	}

	public static final byte toByte(String numString)
	{

		try
		{
			return Byte.parseByte(numString.trim());
		} catch (Exception e)
		{
			e.printStackTrace();
			return 0;
		}
	}

	public static final boolean toBoolean(String boolStr)
	{

		try
		{
			return boolStr.equalsIgnoreCase("true");
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}

	public static final long toLong(String numString)
	{

		try
		{
			return Long.parseLong(numString.trim());
		} catch (Exception e)
		{
			e.printStackTrace();
			return 0;
		}
	}

	public static final Double toDouble(String numString)
	{

		try
		{
			return Double.parseDouble(numString.trim());
		} catch (Exception e)
		{
			e.printStackTrace();
			return 0.0;
		}
	}

	private static final int TIME_OUT = 20000;// ms

	/**
	 * Download file from internet of given url
	 * 
	 * @param fromUrl
	 * @param toPath
	 *            destination path i.e /sdcard/survey/your file
	 * @throws IOException
	 */
	public static void downloadFile(String fromUrl, String toPath)
			throws IOException
	{
		Log.d(Helper.class.getSimpleName(), "Downloading: " + fromUrl);
		InputStream input = null;
		OutputStream output = null;
		try
		{
			URL url1 = new URL(fromUrl);
			URLConnection conexion = url1.openConnection();
			conexion.setConnectTimeout(TIME_OUT);
			conexion.connect();

			input = new BufferedInputStream(url1.openStream());

			output = new FileOutputStream(toPath);

			byte data[] = new byte[512];
			int count = 0;
			while ((count = input.read(data)) != -1)
			{

				output.write(data, 0, count);
			}
		} finally
		{
			if (output != null)
			{
				output.flush();
				output.close();
			}
			if (input != null)
				input.close();
		}

	}

	public static final float toFloat(String numString)
	{

		try
		{
			return Float.parseFloat(numString.trim());
		} catch (Exception e)
		{

			return 0;
		}
	}

	/**
	 * Path to application specific folder with name {@value #APP_FOLDER}
	 * 
	 * @return
	 */
	public static final String getPathToAppFolder()
	{
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ File.separator + APP_FOLDER + File.separator;
	}

	/**
	 * 
	 * @param path
	 * @return
	 */
	public static boolean createDirIfNotExists(String path)
	{
		boolean ret = true;

		File file = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath(), path);

		try
		{
			if (!file.exists())
			{
				if (!file.mkdirs())
				{

					ret = false;
				}
			}
		} catch (SecurityException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}

		return ret;
	}

	/**
	 * For optimization we reduce image quality to not to run Out Of Memory
	 * 
	 * @param file
	 * @param quality
	 *            1 ......n, 1 means maximum quality
	 * @return
	 */
	public static Bitmap decode(String file, int quality)
	{
		BitmapFactory.Options o2 = null;
		try
		{

			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(file, o);

			final int REQUIRED_WIDTH = 320;
			final int REQUIRED_HEIGHT = 480;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;

			int scale = quality;

			scale = quality;
			while (true)
			{
				if (width_tmp / 2 < REQUIRED_WIDTH
						|| height_tmp / 2 < REQUIRED_HEIGHT)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}
			o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
		} catch (Exception e)
		{

		}
		try
		{
			return BitmapFactory.decodeFile(file, o2);
		} catch (Exception e)
		{

			return null;
		}

	}

	/**
	 * 
	 * @param file
	 * @return
	 */
	public static final boolean isFileExist(String file)
	{
		File f = new File(file);
		return f.exists();

	}

	/**
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getTempFile(String fileName)
	{
		String filepath = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator + APP_FOLDER;

		return filepath + File.separator + fileName;
	}

	public static final int getHashNameFromUrl(String url)
	{
		if (url == null)
			url = "";
		if (url.length() == 0)
		{

			return 0;
		}
		return url.hashCode();

	}

	/**
	 * Send get request to download data from server
	 * 
	 * @param url
	 * @param xml
	 * @return
	 * @throws IOException
	 * @throws
	 */
	public static String performGetOperation(String url) throws IOException
	{
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);

		HttpResponse response = client.execute(httpGet);
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		if (statusCode == 200)
		{
			HttpEntity entity = response.getEntity();
			InputStream content = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					content), 1024);
			String line;
			while ((line = reader.readLine()) != null)
			{
				builder.append(line);
			}
		} else
		{
			return null;
		}
		return builder.toString();
	}

	public static InputStream performGetOperationI(String url)
			throws IOException
	{

		HttpClient client = new DefaultHttpClient();

		HttpGet httpGet = new HttpGet(url);

		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
		HttpResponse response = client.execute(httpGet);
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		if (statusCode == 200)
		{

			return response.getEntity().getContent();
		}

		return null;
	}

	/**
	 * 
	 * @param ctx
	 * @return
	 */
	public static boolean isNetworkAvailable(Context ctx)
	{
		NetworkInfo activeNetworkInfo = null;
		try
		{
			ConnectivityManager connectivityManager = (ConnectivityManager) ctx
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

			if (activeNetworkInfo == null)
			{
				return false;
			} else if (!activeNetworkInfo.isConnected())
			{
				return false;
			} else if (!activeNetworkInfo.isAvailable())
			{
				return false;
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}

		return true;
	}

	public static final void delete(File f)
	{
		try
		{
			if (f.isDirectory())
			{
				for (File c : f.listFiles())
					delete(c);
			}
			if (!f.getName().equals(Helper.APP_FOLDER))
				f.delete();
		} catch (Exception e)
		{
			e.printStackTrace();
		}

	}
}
